var currentPage = { NumberPosition: '1' };
var updateData = false;

//reset all variables of tracking data change event
function ResetAllFlags() {
    MarkNoDataChangedInPage();
    hasErrorAfterSaving = false;
    updateData = false;
}

//fire the event when grid is loaded completely
function GridLoadComplete(list, selectedRowId) {
    if (selectedRowId) {
        $(list).jqGrid('setSelection', selectedRowId.Id);
    }
}

function SelectRowOnGrid(rowId, selectedRowId, FillData, list) {
    if (selectedRowId) {
        selectedRowId.Id = rowId;
    }
    ShowHideValidationSummary(false);
    if (typeof FillData == 'undefined' || FillData == null || typeof FillData != 'function')
        return;
    FillData();
}
function HandleError(err, action, entityName) {
    //debugger
    hasErrorAfterSaving = true;
    var responseText = '' + err.responseText;
    if (responseText.indexOf('!DOCTYPE html PUBLIC') > 0) {
        //Get Error from responseText
        var errorString = $('#errorString', $(responseText)).html();
        $("#ValidationSummary").html(errorString).show();
    }
    else if (responseText == 'General failure') {
        OpenAlertPopup("Error", action);
    } else if (action.toLowerCase() != 'loading') {
        OpenAlertPopup(action ? action : "Error", responseText);
    }
}

//Register button click event of east panel
function RegisterButtonClickEastPanel(list, isAutoWidthColumn) {

    $('#toggle-east').bind('click', function () {
        //Check the grid is hidden, don't call AutoSizeFitGrid function()
        if (typeof $(list) == 'undefined' || $(list).length == 0)
            return;
        if ($(list)[0].clientWidth < 100)
            return;

        AutoSizeFitGrid(list, isAutoWidthColumn);
    });

    $('#icoShowTable').bind('click', function () {
        //Check the grid is hidden, don't call AutoSizeFitGrid function()
        if (typeof $(list) == 'undefined' || $(list).length == 0)
            return;
        if ($(list)[0].clientWidth < 100)
            return;
        AutoSizeFitGrid(list, isAutoWidthColumn);
    });

    $('#icoShowSplit').bind('click', function () {
        //Check the grid is hidden, don't call AutoSizeFitGrid function()
        if (typeof $(list) == 'undefined' || $(list).length == 0)
            return;
        if ($(list)[0].clientWidth < 100)
            return;
        AutoSizeFitGrid(list, isAutoWidthColumn);
    });
}

//Sorting columns with data type is boolean
function RegisterSortingBooleanColumn(list) {
    if (typeof $(list)[0] == 'undefined')
        return;
    $("#cb_" + $(list)[0].id).hide();
    $("#jqgh_" + $(list)[0].id + "_cb").addClass("ui-jqgrid-sortable");
    //Sorting columns
    cbColModel = $(list).jqGrid('getColProp', 'cb');
    cbColModel.sortable = true;
    cbColModel.sorttype = function (value, item) {
        return typeof (item.cb) === "boolean" && item.cb ? 1 : 0;
    };
}

//Auto fit width size of grid
function AutoSizeFitGrid(list, isAutoWidthColumn) {
    if (typeof isAutoWidthColumn == 'undefined')
        isAutoWidthColumn = false;
    //Grid will automatic resize by screen.
    $(list).fitWidthSizeGrid({ base: '.grid', offset: -20, id: list, isAutoWidthColumn: isAutoWidthColumn });
}

//Register event OnPagging
function OnPagingEvent(list) {
    if (typeof fnWarningSaveChangedData == 'undefined' || fnWarningSaveChangedData == null)
        return;
    var requestedPage = $(list).getGridParam("page");
    var lastPage = $(list).getGridParam("lastpage");
    var jumpToPage = ((eval(requestedPage) > eval(lastPage)) ? lastPage : requestedPage);
    var editMode = $(list).getGridParam('cellEdit');
    if (editMode == true && fnWarningSaveChangedData != null) {
        fnWarningSaveChangedData();
        if (hasErrorAfterSaving == true) {
            $(list).setGridParam({ page: currentPage.NumberPosition }); //Workaround - jqGrid still increments the page num even when we return stop so we have to reset it (and track the current page num)    
            return 'stop';
        }
    }
}

//Change row's style to zera's style
function RegisterZebraRows(list) {
    $(list + ' tr').removeClass("ui-widget-content");
    $(list + ' tr:nth-child(even)').addClass("evenTableRow");
    $(list + ' tr:nth-child(odd)').addClass("oddTableRow");
}

//default parameters of grid
function GetPostData(list) {
    return {
        sortName: function () { return $(list).jqGrid('getGridParam', 'sortname'); },
        sortOrder: function () { return $(list).jqGrid('getGridParam', 'sortorder'); },
        rowNumber: function () { return $(list).jqGrid('getGridParam', 'rowNum'); },
        rowId: function () {
            return (updateData == true ? selectedRowId.Id : -1);
        },
        page: function () { return $(list).jqGrid('getGridParam', 'page'); }
    };
}
//Multi-Selection
var multiSelection = [];
//the function will be overwrite each page when call RegisterTrackChange function
function GetMultiSelection() {
    return multiSelection;
}

//the function will be overwrite each page when call RegisterTrackChange function
function SetMultiSelection(newValue) {
    multiSelection = newValue;
}

/*======================================================================  
Description : Setup a grid
======================================================================== */
function SetupGrid(gridOptions, GetColumnNames, GetColumnModel, selectedRowId, idsOfSelectedRows, fnFillData, postData, fnWarningSaveChangedData, fnLoadCompleted, isLoadAll, fnOnSelectRow) {
    //Set multi-selection
    SetMultiSelection(idsOfSelectedRows);
    //Set options for grid
    if (gridOptions == null) {
        gridOptions = new Object();
        gridOptions.Title = "";
        gridOptions.Id = "listGrid";
        gridOptions.Url = "#";
        gridOptions.Datatype = 'local';
        gridOptions.Pager = "pagerGrid";
        gridOptions.IsAutoWidthColumn = true;
        gridOptions.IsMultiSelect = false;
        gridOptions.ColumnKeyIndex = "Id";
        gridOptions.DefaultSortName = "Id";
        gridOptions.DefaultSortType = "int";
        gridOptions.DefaultSortOrder = "asc";
        gridOptions.RowNumber = false;
        gridOptions.CheckAllRows = false;
    }
    if (gridOptions.Url == '')
        gridOptions.Url = '#';
    //Configs grid
    $(gridOptions.Id).jqGrid({
        url: gridOptions.Url == '#' ? "" : gridOptions.Url,
        datatype: gridOptions.Url == '#' ? "local" : "json",
        mtype: "post",
        postData: postData ? postData : GetPostData(gridOptions.Id),
        caption: gridOptions.Title == null ? "" : gridOptions.Title,
        // Specify the column names
        colNames: GetColumnNames(),
        // Configure the columns
        colModel: GetColumnModel(),
        ignoreCase: true,
        loadonce: false, // Load once all data
        rowNum: isLoadAll == true ? 10000 : 10,
        rowList: isLoadAll == true ? ['All'] : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
        pager: gridOptions.Pager,
        viewrecords: true,
        width: '100%',
        height: '100%',
        emptyrecords: "<span style='font-weight:bold;color:gray'>There is no record to view.</span>",
        rownumbers: gridOptions.RowNumber == null ? false : gridOptions.RowNumber,
        multiselect: gridOptions.IsMultiSelect,
        scrollrows: true,
        sortable: true,
        sortname: gridOptions.DefaultSortName,
        sorttype: gridOptions.DefaultSortType,
        sortorder: gridOptions.DefaultSortOrder,
        shrinkToFit: true,
        onSelectRow: function (rowId, isSelected) {
            //Multi-Selections
            if (gridOptions.IsMultiSelect) {
                var selections = GetMultiSelection();
                var p = this.p,
                    i = $.inArray(rowId, selections);

                if (!isSelected && i >= 0) {
                    selections.splice(i, 1); // remove id from the list                    
                } else if (i < 0) {
                    selections.push(rowId);                    
                }
                SetMultiSelection(selections);
            }
            //Execute select the row
            SelectRowOnGrid(rowId, selectedRowId, fnFillData, gridOptions.Id);
            //Execute function which is overwritten
            if (typeof (fnOnSelectRow) == 'function') {
                fnOnSelectRow();
            }
        },
        loadError: function (xhr, st, str) {
            HandleError(xhr, "Loading", "");
        },
        loadComplete: function (data) {
            currentPage.NumberPosition = $(gridOptions.Id).getGridParam('page');
            if (gridOptions.IsMultiSelect) {
                //Clear global variable
                if (idsOfSelectedRows == null || idsOfSelectedRows.length == 0) {
                    SetMultiSelection(idsOfSelectedRows);
                }
                //Load multi-check from global variable
                var grid = jQuery(gridOptions.Id);
                var dataIDs = grid.jqGrid('getDataIDs');

                for (i = 0; i < dataIDs.length; i++) {
                    var index = $.inArray(dataIDs[i], GetMultiSelection());
                    if (index > -1) {
                        $(gridOptions.Id).jqGrid('setSelection', dataIDs[i], false);
                    }
                }

            } else {
                GridLoadComplete(gridOptions.Id, selectedRowId);
            }

            //Execute the function which is overwrited each pages
            if (typeof (fnLoadCompleted) == 'function') {
                fnLoadCompleted(data);
            }
            //After setup grid is completed, execute AutoSizeFitGrid function to fit screen of grid
            AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn);
            //Change row's style to zera's style
            RegisterZebraRows(gridOptions.Id);
        },
        onPaging: function (pgButton) {
            // find out the requested and last page
            //OnPagingEvent(gridOptions.Id);
        },
        async: false
    });

    if (gridOptions.CheckAllRows == undefined || gridOptions.CheckAllRows == false) {
        //Sorting columns with data type is boolean
        RegisterSortingBooleanColumn(gridOptions.Id);
    }

    //Set options for footer
    $(gridOptions.Id).jqGrid('navGrid', gridOptions.Pager, { edit: false, add: false, del: false, search: true, beforeRefresh: function () { ClearSearchBeforeRefreshFn(gridOptions.Id) } }, {}, {}, {}, { sopt: ['cn', 'eq', 'lt', 'gt'] });
    //Register event for the button, when user click it, the system will show a popup for user reorder columns.
    ReorderColumns(gridOptions.Id, gridOptions.Pager, gridOptions.IsAutoWidthColumn, GetColumnModel, GetColumnNames);
    //After setup grid is completed, execute AutoSizeFitGrid function to fit screen of grid
    AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn);
    //Register button of east panel on the right screen.
    RegisterButtonClickEastPanel(gridOptions.Id, gridOptions.IsAutoWidthColumn);

    if (gridOptions.exportUrl != '' && gridOptions.exportUrl != undefined && gridOptions.exportUrl != 'undefined') registerExporttoExcel(gridOptions);
}

//register export data to excel file
function registerExporttoExcel(gridOption) {

    $(gridOption.Id).jqGrid('navButtonAdd', gridOption.Pager, {
        caption: "Export to Excel",
        buttonicon: "ui-icon-bookmark",
        title: "Export to Excel",
        onClickButton: function () {
            var recordnumber = $(gridOption.Id).getGridParam("reccount");
            if (recordnumber < 1) {
                alert('There is no record to export.');
                return;
            }
            var url = gridOption.exportUrl + '?';
            var gridparams = $(gridOption.Id).getGridParam("postData");

            $.each(gridparams, function (key, value) {
                if ($.isFunction(value))
                    url += key + "=" + encodeURIComponent(value()) + "&";
                else
                    url += key + "=" + encodeURIComponent(value) + "&";
            });

            //get columnNames and columnCaptions display.
            var _ColumnNames = '';
            var _ColumnCaptions = '';
            var listColName = $(gridOption.Id).jqGrid('getGridParam', 'colModel');
            var listColCaption = $(gridOption.Id).jqGrid('getGridParam', 'colNames');

            var idx = 0;
            if (gridOption.IsMultiSelect) idx = 1;

            for (var i = idx; i < listColName.length; i++) {
                if (listColName[i].hidden == false) {
                    _ColumnNames += listColName[i].index + ';';
                    _ColumnCaptions += listColCaption[i] + ';';
                }
            }

            if (_ColumnNames != '') _ColumnNames = _ColumnNames.substring(0, _ColumnNames.length - 1);
            if (_ColumnCaptions != '') _ColumnCaptions = _ColumnCaptions.substring(0, _ColumnCaptions.length - 1);

            url += 'ColumnNames=' + encodeURIComponent(_ColumnNames) + '&ColumnCaptions=' + encodeURIComponent(_ColumnCaptions);

            if (url != '') {
                window.open(url, '_blank');
            }
        }
    });
}

//Display a popup to choose columns what user wants to view
function ReorderColumns(list, pager, isAutoWidthColumn, GetColumnModel, GetColumnNames) {

    if (typeof GetColumnModel != "function")
        return false;
    var gridName = list.replace('#', '');

    $(list).jqGrid('navButtonAdd', pager, {
        caption: "",
        title: "Reorder Columns",
        onClickButton: function () {
            jQuery(list).jqGrid('columnChooser', {
                done: function () {
                    AutoSizeFitGrid(list, isAutoWidthColumn);
                },
                dialog_opts: {
                    create: function () { GeneralColumnReorder(list, GetColumnModel, GetColumnNames) },
                    modal: true,
                    minWidth: 470,
                    show: 'blind',
                    hide: 'explode'
                }
            });
        }
    });
}

//Fix problem of gird : When user clicks refresh button, the search popup doesn't clear info of user input
function ClearSearchBeforeRefreshFn(list) {
    var gridName = list.replace('#', '');
    $('#fbox_' + gridName + '_reset').click();
}
//Clear search box of jqgrid
function ClearSearchFilterGird(selector) {
    var gridName = selector.replace('#', '');
    $("#fbox_" + gridName).jqFilter('resetFilter');
}

//when columnChooser function is executed, all columns will be loaded in popup.
//the function will be used for removing columns have to reorder property is false
function GeneralColumnReorder(list, GetColumnModel, GetColumnNames) {
    var gridName = list.replace('#', '');
    var columnReorder = GetColumnModel();
    var columnNames = GetColumnNames();

    //columnClone = columnReorder;
    var listColRemove = new Array();
    for (var i = 0; i < columnReorder.length; i++) {

        var isHidden = (typeof columnReorder[i].hidden == "undefined") ? false : columnReorder[i].hidden;
        if (isHidden) {
            var columnName = columnNames[i];
            var val = FindIndexDropdownlistByText(list, columnName, columnReorder);
            if (val < 0) {
                continue;
            }
            listColRemove.push(val);
        }
    }
    //colchooser_jgPendingTickets
    for (var z = 0; z < listColRemove.length; z++) {
        $('#colchooser_' + gridName + ' select option[value="' + listColRemove[z] + '"]').remove();
    }
}

function FindIndexDropdownlistByText(list, text, columnReorder) {
    var gridName = list.replace('#', '');
    var val = -1;
    $('#colchooser_' + gridName + ' select option').each(function (i) {
        if ($(this).text() == text) {
            val = parseInt($(this).val());
        }
    });
    return val;
}

/*
SUPPORT FUNCTIONS
*/

function GetGridSelections(list) {
    return $(list).jqGrid('getGridParam', 'selarrrow');
}

function GetDataSelections(list) {
    var data = [];
    var ids = $(list).jqGrid('getGridParam', 'selarrrow');
    $.each(ids, function (i, item) {
        var rawData = $(list).getRowData(item);
        data.push(rawData);
    });
    return data;
}

function SetTooltipForGrid(val) {
    var tooltip = val.replace(/\'/g, '');
    tooltip = val.replace(/\"/g, '');
    return String.format('title="{0}"', tooltip);
}

//Refresh grid
function TriggerReloadDataGrid(list) {
    ShowHideValidationSummary(false);
    $(list).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}

//Load grid by json data 
function LoadJsonDataForGrid(selector, mydata) {
    $(selector).clearGridData();
    for (var i = 0; i <= mydata.length; i++)
        $(selector).jqGrid('addRowData', i + 1, mydata[i]);
}


//Support get list of ids when grid can multi-select
function GetListIDBySelected(list) {
    var ids = jQuery(list).jqGrid('getGridParam', 'selarrrow');
    return ids;
}

//The function will be used for grid which can editabled
function Regis(next, SaveEditValueInCurrentCell) {
    $(next).click(function () {
        SaveEditValueInCurrentCell();
    });
}

function RegisterOnAfterSaveCellInGrid(list, DoOnAfterSaveCell) {
    $(list).setGridParam({
        afterSaveCell: DoOnAfterSaveCell
    });
}

function SetUrlForGrid(list, urlAction) {
    if (urlAction == '#') {
        $(list).setGridParam({ url: '', datatype: 'local' });
    }
    else {
        $(list).setGridParam({ url: urlAction, datatype: 'json' });
    }
    TriggerReloadDataGrid(list);
}

function SetHeightOfGrid(list, height) {
    $(list).setGridHeight(height);
}
function SetWidthOfGrid(list, width) {
    $(list).setGridWidth(width, false);
}

function SetEditableGrid(list, afterEditCellFunc) {
    $(list).setGridParam({
        cellEdit: true,
        cellsubmit: 'clientArray',
        afterEditCell: afterEditCellFunc
    });
}

function SetSaveEditableGrid(list, afterSaveCellFunc) {
    $(list).setGridParam({
        cellEdit: true,
        cellsubmit: 'clientArray',
        afterSaveCell: afterSaveCellFunc
    });
}

function RegisterOnBeforeEditCell(list, onBeforeEditCellFunc) {
    $(list).setGridParam({
        beforeEditCell: onBeforeEditCellFunc
    });
}

function GetSelectedRowId(list) {
    return $(list).jqGrid('getGridParam', 'selrow');
}

function GetRowId(list, columnIdName) {
    var grid = jQuery(list);
    var sel_id = grid.jqGrid('getGridParam', 'selrow');
    return grid.jqGrid('getCell', sel_id, columnIdName);
}

function GetCellValue(list, rowId, columnIdName) {
    var rowData = jQuery(list).getRowData(rowId);
    return rowData[columnIdName];
}

function SetCellValue(list, rowId, columnIdName, value) {
    var grid = jQuery(list);
    grid.jqGrid('setCellValue', rowId, columnIdName, value);
}

function DeleteRows(selector, ids) {
    var list;
    if (ids == null || ids == 'undefined') {
        list = GetListIDBySelected(selector);
    }
    else {
        list = ids;
    }
    for (var i = list.length - 1; i >= 0; i--) {
        var col = jQuery(selector).jqGrid('delRowData', list[i]);
    }
}

function DeleteRow(selector, id) {
    selector.jqGrid('delRowData', id);
}

function CountRecords(selector) {
    return selector.getGridParam("reccount");
}

function SumValuesCol(selector, columnName) {
    return selector.jqGrid('getCol', columnName, false, 'sum');
}

// Copy Data to grid
function LoadDataForGrid(selector, mydata) {
    $(selector).clearGridData();
    for (var i = 0; i <= mydata.length; i++) {
        $(selector).jqGrid('addRowData', i + 1, mydata[i]);
    }
    $(selector).trigger('reloadGrid');
}

function LoadDataJsonForGrid(selector, mydata) {
    $(selector).clearGridData();
    var data = mydata.rows;
    for (var i = 0; i <= data.length; i++) {
        $(selector).jqGrid('addRowData', i + 1, data[i]);
    }
    $(selector).trigger('reloadGrid');
}

function ClearDataGrid(selector) {
    var grid = $(selector);
    grid.clearGridData();
    grid.trigger('reloadGrid');
}

function ReloadGridView(selector, actionUrl, opts, fnLoadComplete) {
    var grid = $(selector);
    grid.clearGridData();
    grid.setGridParam({ url: actionUrl });
    grid.setGridParam({ postData: opts });
    grid.setGridParam({ datatype: 'json' });
    grid.setGridParam({ loadComplete: function () {
        if (typeof (fnLoadComplete) == 'function') {
            fnLoadComplete();
        }
    }
    });
    grid.trigger('reloadGrid');
}

/* 
Check all checkboxes in grid
*/
function SetSelectionForAllRows(grid) {
    grid.resetSelection();
    var ids = grid.getDataIDs();
    for (var i = 0, il = ids.length; i < il; i++)
        grid.setSelection(ids[i], false);
}

/* 
User for color coding
*/
function RenderCellBackgroundColor(cellvalue, dataRow, index, isBlinking) {
    if (isBlinking)
        return '<span class="CellBackgroundColorBlinking" style="background-color: ' + dataRow[index] + ';">' + cellvalue + '</span>';
    return '<span class="CellBackgroundColor" style="background-color: ' + dataRow[index] + ';">' + cellvalue + '</span>';
}
